using System.Collections.Generic;
using System.Data.Linq.Mapping;
using System.Linq;
using Magiq.Databases;

namespace Magiq.Providers.Sql.Support
{
    public class SqlTypeMapping : ITypeMapping
    {
        private readonly MetaType metaType;
        private IEnumerable<MetaDataMember> persistentDataMembers;

        public SqlTypeMapping(MetaType metaType)
        {
            this.metaType = metaType;
        }

        private IEnumerable<MetaDataMember> PersistentDataMembers
        {
            get
            {
                if (persistentDataMembers == null)
                    persistentDataMembers = metaType.DataMembers;

                return persistentDataMembers;
            }
        }

        #region ITypeMapping Members

        public IEnumerable<PropertyMapping> Members
        {
            get { return MappingsOf(metaType.DataMembers); }
        }

        public string TableName
        {
            get { return metaType.Table.TableName; }
        }

        public bool IsEntity
        {
            get { return metaType.IsEntity; }
        }

        public IEnumerable<PropertyMapping> Ids
        {
            get { return MappingsOf(metaType.IdentityMembers); }
        }

        public IEnumerable<string> ColumnsFor(string propertyName)
        {
            var dataMember = PersistentDataMembers.Single(x => x.Name == propertyName);

            return dataMember.IsAssociation
                       ? dataMember.Association.ThisKey.Select(x => x.MappedName)
                       : new[] {dataMember.MappedName};
        }

        #endregion

        private static IEnumerable<PropertyMapping> MappingsOf(IEnumerable<MetaDataMember> members)
        {
            return members.Select(x => new PropertyMapping(x.Name, x.Type));
        }

        public string ColumnFor(string propertyName)
        {
            return ColumnsFor(propertyName).FirstOrDefault();
        }
    }
}